﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;

namespace LiteratureManage.Web.Initialization
{
    using Castle.Core;
    using Castle.Windsor;
    using FluentValidation;

    public class ServiceLocatorValidatorFactory : ValidatorFactoryBase
    {
        private readonly IList<string> _validatorTypes;
        private readonly IWindsorContainer _container;

        public ServiceLocatorValidatorFactory(IWindsorContainer container)
        {
            this._container = container;
            this._validatorTypes = new List<string>();
            var validatorScanResults = AssemblyScanner.FindValidatorsInAssembly(Assembly.GetExecutingAssembly());
            if (validatorScanResults != null)
            {
                foreach (var t in validatorScanResults)
                {
                    //register all validator types
                    this._container.AddComponentLifeStyle(t.ValidatorType.FullName, t.InterfaceType, t.ValidatorType, LifestyleType.Singleton);
                    this._validatorTypes.Add(t.InterfaceType.AssemblyQualifiedName);
                }
            }
        }

        public override IValidator CreateInstance(Type validatorType)
        {
            IValidator validator = null;
            if (this._validatorTypes.Contains(validatorType.AssemblyQualifiedName))
                validator = this._container.Resolve(validatorType) as IValidator;
            return validator;
        }
    }
}
